package com.zhangpu.zuul.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author: zhangpu
 * @License: (C) Copyright hualala.com Corporation Limited.
 * @Contact: zhangpu@hualala.com
 * @Date: 2021.07.20 18:49
 * @Version: 1.0
 * @Description: 网关过滤器
 * @ProjectName: spring-cloud-eureka
 */

@Component
public class MyFilter extends ZuulFilter {

    private static Logger log=LoggerFactory.getLogger(MyFilter.class);

    /**
     * filterType返回一个字符串代表的过滤器的类型，在zuul中定义了四种不同生命周期的过滤器类型，
     * pre 路由之前
     * routing 路由之时
     * post 路由之后
     * error 发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return "事先处理";
    }

    /**
     *  过滤的顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 这里可以写逻辑判断，是否需要过滤。true表示永远需要过滤，false表示不需要
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * run是过滤器的具体逻辑，可用很复杂，包括查询sql，nosql 去判断该请求到底有没有权限访问
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx=RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        log.info(String.format("%s>>>%s",request.getMethod(),request.getRequestURI().toString()));
        Object accessToken=request.getParameter("token");
        if(Objects.isNull(accessToken)){
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            } catch (IOException e) {
                log.error("网关在处理过滤的时候出错了",e);
            }
        }
        log.info("ok");
        return null;
    }
}